import React, {
  // eslint-disable-next-line no-unused-vars
  createContext, useContext, useState, useEffect, Context, ReactNode,
} from 'react';

import AppTheme from './AppThemeMode';
// eslint-disable-next-line no-unused-vars
import { AppThemeMode } from './Contants';

type ContextType = AppThemeMode | 'current'
export const DarkModeContext: Context<ContextType> = createContext<ContextType>('current');
DarkModeContext.displayName = 'DarkModeContext';

interface IProps { mode?: AppThemeMode; children: ReactNode; }

function useCurrentMode(forcedMode?: AppThemeMode) {
  const [currentMode, setCurrentMode] = useState<AppThemeMode>(AppTheme.currentMode);

  useEffect(() => {
    if (forcedMode) return;
    if (currentMode !== AppTheme.currentMode) {
      setCurrentMode(AppTheme.currentMode);
    }

    function handler(mode: AppThemeMode) {
      // console.log('handler', mode);
      setCurrentMode(mode);
    }

    AppTheme.addListener(handler);

    // eslint-disable-next-line consistent-return
    return () => {
      AppTheme.removeListener(handler);
    };
  });
  // [currentMode, forcedMode]
  // console.log('useCurrentMode', currentMode);
  return currentMode;
}

export function DarkModeProvider({ children, mode }: IProps) {
  const currentMode = useCurrentMode(mode);

  return (
    <DarkModeContext.Provider value={mode || currentMode}>
      {children}
    </DarkModeContext.Provider>
  );
}

export function useDarkModeContext(): AppThemeMode {
  const context = useContext(DarkModeContext);
  const currentMode = useCurrentMode(context === 'current' ? undefined : context);
  // console.log('useDarkModeContext', currentMode);
  if (context === 'current') {
    return currentMode;
  }

  return context;
}
